package com.aweqy.librarymanager.controller;

import com.aweqy.librarymanager.entity.BorrowRecord;
import com.aweqy.librarymanager.service.BorrowRecordService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/api/borrow")
public class BorrowRecordController {
    @Autowired
    private BorrowRecordService borrowRecordService;

    // 借书
    @PostMapping("/borrow")
    public boolean borrow(@RequestBody BorrowRecord record) {
        record.setBorrowTime(new Date());
        record.setStatus(1); // 借阅中
        return borrowRecordService.save(record);
    }

    // 续借
    @PostMapping("/renew")
    public boolean renew(@RequestBody Map<String, Object> params) {
        Integer recordId = (Integer) params.get("recordId");
        BorrowRecord record = borrowRecordService.getById(recordId);
        if (record != null && record.getStatus() == 1) {
            record.setRenewCount(record.getRenewCount() + 1);
            record.setLastRenewTime(new Date());
            // 这里可根据业务延长planReturnTime
            borrowRecordService.updateById(record);
            return true;
        }
        return false;
    }

    // 归还
    @PostMapping("/return")
    public boolean returnBook(@RequestBody Map<String, Object> params) {
        Integer recordId = (Integer) params.get("recordId");
        BorrowRecord record = borrowRecordService.getById(recordId);
        if (record != null && record.getStatus() == 1) {
            record.setActualReturnTime(new Date());
            record.setStatus(2); // 已归还
            borrowRecordService.updateById(record);
            return true;
        }
        return false;
    }

    // 借阅记录查询
    @GetMapping("/records")
    public Page<BorrowRecord> records(@RequestParam(defaultValue = "1") int page,
                                      @RequestParam(defaultValue = "10") int size,
                                      @RequestParam(required = false) Integer borrowerId) {
        QueryWrapper<BorrowRecord> wrapper = new QueryWrapper<>();
        if (borrowerId != null) {
            wrapper.eq("borrower_id", borrowerId);
        }
        return borrowRecordService.page(new Page<>(page, size), wrapper);
    }

    // 删除借阅记录
    @PostMapping("/delete")
    public ResponseEntity<?> delete(@RequestBody Map<String, Object> params) {
        Integer recordId = (Integer) params.get("recordId");
        if (recordId == null) {
            return ResponseEntity.badRequest().body("参数错误，缺少recordId");
        }
        boolean ok = borrowRecordService.removeById(recordId);
        if (!ok) {
            return ResponseEntity.status(500).body("删除失败");
        }
        return ResponseEntity.ok(true);
    }
} 